package com.aaa.mrcai.service.impl;

import com.aaa.mrcai.mapper.EnrollMapper;
import com.aaa.mrcai.pojo.vo.EnrollVo;
import com.aaa.mrcai.result.AjaxResult;
import com.aaa.mrcai.service.EnrollService;
import com.aaa.mrcai.util.SendCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletContext;

/**
 * Demo class
 *
 * @Author: Wang
 * @Date: Created in 21:16 2021/12/10
 */
@Service
public class EnrollerServiceImpl implements EnrollService {
    @Autowired
    private ServletContext servletContext;


    @Autowired
    private EnrollMapper enrollMapper;

    @Override
    public AjaxResult enroll(EnrollVo enrollVo) {

        long exists = enrollMapper.isTelephoneExists(enrollVo.getTelephone());
        if (exists > 0) {
            return AjaxResult.defeated("手机号已存在");
        }
//        System.out.println(enrollVo.getCode());//输入框中填写的验证码



            Object attribute = servletContext.getAttribute(enrollVo.getTelephone());
            //手机号获取到的验证码

//        System.out.println(attribute);

            if (attribute == null) {
                return AjaxResult.defeated("请输入验证码");
            }
            if (!attribute.equals(enrollVo.getCode())) {
                return AjaxResult.defeated("验证码错误");
            } else {
                int i = enrollMapper.enrollVo(enrollVo);
                Integer id = enrollVo.getId();

                int i2 = enrollMapper.addUserInfo(id);

                enrollVo.setUid(id);
                int i1 = enrollMapper.updateUid(enrollVo);
                if (i1> 0) {
                    return AjaxResult.success("注册成功");
                }
                return AjaxResult.defeated("检查后重试");
            }
        }


    @Override
    public AjaxResult isTelephoneExists(String telephone) {
        long exists = enrollMapper.isTelephoneExists(telephone);
        if (exists>0){
            return AjaxResult.defeated("手机号已存在");
        }

        return AjaxResult.success();
    }

    @Override
    public AjaxResult sendCode(String telephone) {
        int random = (int) (Math.random()*1000000);
        System.out.println(random);
        int i = SendCodeUtil.sendCode(random, telephone);
        if (i>0){
            servletContext.setAttribute(telephone,random);
            return AjaxResult.success("验证码发送成功");
        }
        return AjaxResult.defeated("验证码发送失败");
    }





}
